package com.css.spring.formework.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

public class ProxyUtils {
    public static Object getTargetObject(Object proxy) throws NoSuchFieldException, IllegalAccessException {
        //css// 先判断对象是不是代理对象
        if (!isProxyObject(proxy)) {
            return proxy;
        } else {
            return getProxyTargetObject(proxy);
        }
    }

    private static boolean isProxyObject(Object proxy) {
        return Proxy.isProxyClass(proxy.getClass());
    }

    public static Object getProxyTargetObject(Object proxy) throws NoSuchFieldException, IllegalAccessException {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");

        h.setAccessible(true);
        AopProxy aopProxy = (AopProxy) h.get(proxy);
        Field target = aopProxy.getClass().getDeclaredField("target");
        target.setAccessible(true);
        return target.get(aopProxy);
    }

}
